package com.enzoism.springboot.juc;

import java.time.Instant;
import java.util.concurrent.*;

public class MyThreadPoolExecutor3 {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 20;
    private static final int QUEUE_CAPACITY = 20;
    private static final int KEEP_ALIVE_TIME = 200;

    public static void main(String[] args) throws InterruptedException {

        // 1、常用线程操作
        ExecutorService executorService = Executors.newCachedThreadPool();
        ExecutorService executorService1 = Executors.newFixedThreadPool(CORE_POOL_SIZE);
        ExecutorService executorService2 = Executors.newSingleThreadExecutor();
        ExecutorService executorService3 = Executors.newWorkStealingPool();
        for (int i = 0; i < 20; i++) {
            executorService.execute(new MyRunable());
        }
        executorService.shutdown();
        executorService.awaitTermination(200, TimeUnit.SECONDS);
        System.out.println("----->线程结束退出");

        // 2、定时任务操作+原生的调度类
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(CORE_POOL_SIZE);
        ScheduledExecutorService scheduledExecutorService1 = Executors.newSingleThreadScheduledExecutor();
        ScheduledExecutorService scheduledExecutorService2 = new ScheduledThreadPoolExecutor(CORE_POOL_SIZE);
        // 因为没有配置周期，立即执行
        scheduledExecutorService.execute(new MyRunable());
        scheduledExecutorService.schedule(new MyRunable(), 20, TimeUnit.SECONDS);
        // 第一次延迟20s,然后每隔5时间就提交下次任务【固定执行period任务周期】
        scheduledExecutorService.scheduleAtFixedRate(new MyRunable(), 20, 5, TimeUnit.SECONDS);
        // 第一次延迟20s,然后任务接收后和下次任务之间等待5s【delay 一次执行终止和下一次执行开始之间的延迟】
        // scheduleWithFixedDelay 比如当前一个任务结束的时刻，开始结算间隔时间，如0秒开始执行第一次任务，任务耗时5秒，任务间隔时间3秒，那么第二次任务执行的时间是在第8秒开始。
        scheduledExecutorService.scheduleWithFixedDelay(new MyRunable(), 20, 5, TimeUnit.SECONDS);


    }

    private static class MyRunable implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("----->Current Thread Name:" + Thread.currentThread().getName() + " date:" + Instant.now());
        }
    }
}
